<?php

namespace app\index\model;

use think\Model;
use think\facade\Config;
use think\facade\Session;

use app\index\validate\User as Validate;

class User extends Model
{
    // 指定时间戳输入格式化类名
    public $dateFormat = '\app\index\model\dateFormat';

    /**
     * 验证字段值是否唯一
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-16
     * @param    [type]             $data [description]
     * @param    integer            $id   [description]
     * @return   [type]                   [description]
     */
    public function checkFieldUnique($data, $id = 0)
    {
        $field_name = null;
        if(!isset($data['field'])){
            return false;
        }
        $field_name = $data['field'];

        if(!isset($data[$field_name])){
            return false;
        }
        $field_value = $data[$field_name];

        $query = $this->where($field_name, $field_value);
        if($id > 0){
            $query = $this->where('id', '<>', $id);
        }

        if($query->count()){
            return false;
        }

        return true;
    }

    /**
     * 注册新用户
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-15
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
     */
    public function register($data)
    {
        $res = new FunctionResult('新用户注册失败');

        $validate = new Validate;
        if(!$validate->check($data)){
            $res->fail($validate->getError(), []);
            return $res;
        }

        // 对登录密码加密
        $data['password'] = $this->md5Password($data['password']);
        $this->save($data);

        $res->success('新用户注册成功', ['id' => $this->id]);
        return $res;
    }

    /**
     * 用户登录
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-16
     * @param    string             $mobile   登录手机号码
     * @param    string             $password 登录密码
     * @return   object                       FunctionResult
     */
    public function login($mobile, $password)
    {
        $res = new FunctionResult('登录失败');
        if(empty($mobile)){
            $res->fail('登录手机不能为空');
            return $res;
        }else if(empty($password)){
            $res->fail('登录密码不能为空');
            return $res;
        }

        $user = $this->field(['id', 'name', 'avatar', 'mobile', 'password'])
                    ->where('mobile', $mobile)->find();
        if(empty($user)){
            $res->fail('登录手机或密码错误');
            return $res;
        }else if($user['password'] != $this->md5Password($password)){
            $res->fail('登录手机或密码错误');
            return $res;
        }

        unset($user['password']);
        // 注意$user是Object，不是数组
        $res->success('登录成功', ['user' => $user]);
        return $res;
    }

    /**
     * 系统当前登录用户
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-27
     * @return   [type]             [description]
     */
    static public function currentUser()
    {
        return Session::get('current_user');
    }

    /**
     * 重置用户登录密码
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-16
     * @param    array               $data 表单提交数据
     * @return   object                    FunctionResult
     */
    public function resetPassword($data)
    {
        $res = new FunctionResult('重置登录密码失败');

        if(!isset($data['mobile'])){
            $res->fail('登录手机不能为空');
            return $res;
        }

        $mobile = $data['mobile'];
        $user = $this->field(['id', 'name', 'mobile', 'password'])
                    ->where('mobile', $mobile)->find();
        if(empty($user)){
            $res->fail('登录手机或密码错误');
            return $res;
        }

        $validate = new Validate;
        if(!$validate->scene('reset_password')->check($data)){
            $res->fail($validate->getError(), []);
            return $res;
        }

        $user->password = $this->md5Password($data['password']);
        $user->save();

        $res->success('重置登录密码成功');
        return $res;
    }

    /**
     * 更新用户基础信息--类方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-17
     * @param    integer            $id   用户ID
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
     */
    static function updateItem($id, $data)
    {
        $res = new FunctionResult('更新用户信息失败');

        $user = self::find($id);
        if(empty($user)){
            $res->fail('未找到注册用户信息');
            return $res;
        }
        return $user->updateInfo($data);
    }

    /**
     * 更新用户基础信息--实例方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-17
     * @param    array              $data 表单提交数据
     * @return   Object                   FunctionResult
     */
    public function updateInfo($data)
    {
        $res = new FunctionResult('更新个人信息失败');

        $validate = new Validate;
        if(!$validate->scene('update')->check($data)){
            $res->fail($validate->getError(), []);
            return $res;
        }

        $this->save($data, ['id' => $this->id]);
        $res->success('更新个人信息成功');
        return $res;
    }

    /**
     * 生成密码加密结果
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-16
     * @param    string             $password 登录密码
     * @param    string             $authcode 加密key
     * @return   string                       加密后的密码
     */
    private function md5Password($password, $authcode = '')
    {
        if(empty($authcode)){
            $authcode = Config::get('app.authcode');
        }
        $result = "###".md5(md5($authcode.$password));
        return $result;
    }
}
